"use strict";

import Vue from 'vue';
import axios from "axios";
import qs from "qs";
import { Message } from 'element-ui';

// const baseHost = 'http://data.shengqiancucu.com';
const baseURL = 'http://psy-data.cy66688.cn';
const imgURL = 'http://psy-data.cy66688.cn/local-image-proxy?file=';
// const baseURL = 'http://localhost:9096';
// const imgURL = 'http://localhost:9096/local-image-proxy?file=';
const _axios = axios.create({
  baseURL: baseURL,
  imgURL: imgURL,
  timeout: 15 * 1000,
  withCredentials: false, // Check cross-site Access-Control
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

const _upload = axios.create({
  baseURL: baseURL,
  timeout: 15000,
  withCredentials: false, // Check cross-site Access-Control
  headers: {
    'Content-Type': 'multipart/form-data'
  }
});

let responseFilter = (response)=> {
  let data = response.data;
  if (data) {
    // 消息解析
    if (data.message && data.message.type) {
      Message({
        message: data.message.content,
        type: data.message.type
      });
    }
    // 错误码
    if (data.err_msg && data.err_code) {
      Message({
        message: data.err_code + ": " + data.err_msg,
        type: "warning"
      })
    }
    // 字段验证
    if (data.Field && data.Message) {
      Message({
        message: data.Field + ": " + data.Message,
        type: "warning"
      })
    }
    return response
  }
};

let requestParser = (config) => {
  let method = config.method.toUpperCase();
  if (method === "POST" || method==="PUT") {
    config.data = qs.stringify(config.data,{arrayFormat: 'brackets'});
  }
  return config;
};

_axios.interceptors.request.use(requestParser,  (error) => {
  return Promise.reject(error);
});

// Add a response interceptor
_axios.interceptors.response.use(responseFilter,
  function(error) {
    return Promise.reject(error);
  }
);

// Add a response interceptor
_upload.interceptors.response.use(responseFilter,
    function(error) {
      return Promise.reject(error);
    }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  Vue.upload = _upload;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    // ajax 组件
    $axios: {
      get() {
        return _axios;
      }
    },
    // 上传文件组件
    $upload: {
      get() {
        return _upload;
      }
    },
    // 检测是否响应 success 消息
    $isSuccessMsg: {
      get() {
        return (response)=>{
          let data =response.data;
          return data&&data.message&&data.message.type==="success"
        }
      }
    },
    // element ui 上传文件方法
    $uploadElementItem: {
      get() {
        return (item)=>{
            let formData = new FormData();
            formData.append(item.filename, item.file);
            for(let key in item.data) {
              formData.append(key, item.data[key]);
            }
            return this.$upload .post(item.action, formData)
        }
      }
    },
  });
};

Vue.use(Plugin);

export default Plugin;
